<template>
	<view class="address-list-page">
		<view class="address-list" v-if="addresses.length > 0">
			<view class="address-item"
				  v-for="(address, index) in addresses"
				  :key="index"
				  @click="isManaging ? toggleSelect(address) : selectAddress(address)"> <!-- 根据状态切换点击行为 -->

				<!-- 管理模式下的选择框 -->
				<view class="checkbox-wrapper" v-if="isManaging" @click.stop="toggleSelect(address)">
					<view :class="['checkbox', address.selected ? 'checked' : '']">
						<uni-icons v-if="address.selected" type="checkmarkempty" size="20" color="#fff"></uni-icons>
					</view>
				</view>

				<view class="address-info">
					<view class="contact-line">
						<text class="name">{{ address.name }}</text>
						<text class="phone">{{ address.phone }}</text>
						<text class="tag default-tag" v-if="address.isDefault">默认</text>
					</view>
					<view class="address-detail">
						{{ address.province }} {{ address.city }} {{ address.district }} {{ address.street }} {{ address.detailAddress }}
					</view>
				</view>
				<!-- 非管理模式下的编辑按钮 -->
				<view class="edit-action" v-if="!isManaging" @click.stop="editAddress(address)"> <!-- 阻止事件冒泡 -->
					<uni-icons type="compose" size="22" color="#909399"></uni-icons>
				</view>
			</view>
		</view>
		<view class="empty-state" v-else>
			<image class="empty-icon" src="/static/empty_address.png" mode="widthFix"></image> <!-- 替换为你的空状态图 -->
			<text class="empty-text">还没有收货地址哦</text>
		</view>

		<!-- 底部操作栏 -->
		<view :class="['bottom-actions', isManaging ? 'bottom-actions-manage' : '']">
			<template v-if="!isManaging">
				<button class="manage-btn" @click="startManage" :disabled="addresses.length === 0">管理</button>
				<button class="add-btn" @click="addAddress">
					<uni-icons type="plus" size="18" color="#303133" style="margin-right: 8rpx;"></uni-icons> <!-- 图标颜色与按钮文字颜色一致 -->
					添加收货地址
				</button>
			</template>
			<template v-else>
				<button class="cancel-btn" @click="cancelManage">取消</button>
				<button class="delete-btn" @click="deleteSelectedAddresses" :disabled="selectedAddresses.length === 0">删除 ({{ selectedAddresses.length }})</button>
			</template>
		</view>
		<!-- 占位，防止底部内容被悬浮栏遮挡 -->
		<view :style="{ height: bottomBarHeight + 'px' }"></view>

		<!-- 添加/编辑地址弹窗 -->
		<uni-popup ref="addressPopup" type="bottom" :mask-click="false">
			<view class="address-form-popup">
				<view class="popup-header">
					<text class="title">{{ isEditing ? '编辑收货地址' : '添加收货地址' }}</text>
					<uni-icons type="close" size="24" color="#999" @click="closeAddressForm"></uni-icons>
				</view>
				<view class="popup-body">
					<uni-forms ref="form" :modelValue="currentAddress" :rules="addressRules" validate-trigger="submit">
						<uni-forms-item label="收货人" name="name" required>
							<uni-easyinput v-model="currentAddress.name" placeholder="请填写收货人姓名"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item label="手机号码" name="phone" required>
							<uni-easyinput v-model="currentAddress.phone" placeholder="请填写手机号码" type="number" maxlength="11"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item label="所在地区" name="region" required>
							<!-- 这里使用uni-data-picker作为省市区选择器 -->
							<!-- 需要提供本地的 region data 或者从接口获取 -->
							<!-- 示例中regionData使用假数据，实际需要替换 -->
							 
							<uni-data-picker
								mode="region"
								v-model="currentAddress.region"
								:localdata="regionData"
								placeholder="请选择省/市/区"
								@change="onRegionChange"
								:clear-icon="false"
							></uni-data-picker>
						</uni-forms-item>
						<uni-forms-item label="详细地址" name="detailAddress" required>
							<uni-easyinput type="textarea" v-model="currentAddress.detailAddress" placeholder="街道、楼牌号等"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item label="设为默认地址">
							<switch :checked="currentAddress.isDefault" @change="onDefaultChange" color="#ffc800" style="transform:scale(0.8)"></switch>
						</uni-forms-item>
					</uni-forms>
				</view>
				<view class="popup-footer">
					<button class="save-btn" @click="saveAddress">保存地址</button>
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
import regionData from '@/common/region-data';
const app = getApp()
export default {
	components: {
	},
	data() {
		return {
			isManaging: false, // 是否处于管理模式
			addresses: [],
			bottomBarHeight: 60, // 预估底部操作栏高度
			showAddressForm: false, // 控制地址弹窗显示
			currentAddress: {}, // 当前正在编辑或添加的地址对象
			isEditing: false, // 是否处于编辑状态
			regionData: regionData.data, // 省市区数据
			addressRules: { // 表单校验规则
				name: {
					rules: [{ required: true, errorMessage: '请输入收货人姓名' }]
				},
				phone: {
					rules: [
						{ required: true, errorMessage: '请输入手机号码' },
						{ pattern: /^1\d{10}$/, errorMessage: '请输入正确的手机号码' }
					]
				},
				// region: { // uni-data-picker 绑定 v-model 后会自动校验是否选择
				// 	rules: [{ required: true, errorMessage: '请选择所在地区' }]
				// },
				detailAddress: {
					rules: [{ required: true, errorMessage: '请输入详细地址' }]
				}
			}
		};
	},
	computed: {
		selectedAddresses() {
			return this.addresses.filter(addr => addr.selected);
		}
	},
	onShow(){
		this.getAddressList()
	},
	onLoad() {
		console.log(regionData)
		uni.setNavigationBarTitle({
			title: '我的收货地址'
		});
		// 初始化地址数据时，添加 selected 属性
		this.addresses.forEach(addr => {
			addr.selected = false;
			if (!addr.region) {
				// 简单示例，实际应更复杂
				addr.region = this.findRegionValue(addr.province, addr.city, addr.district);
			}
		});
	},
	onReady() {
		// 获取底部操作栏实际高度
		const query = uni.createSelectorQuery().in(this);
		query.select('.bottom-actions').boundingClientRect(data => {
		  if (data && data.height) {
		    // 加一点padding和安全区高度
		    this.bottomBarHeight = data.height + (uni.getSystemInfoSync().safeAreaInsets?.bottom || 0);
		  }
		}).exec();
	},
	methods: {
		getAddressList(){
			app.globalData.Request.post(app.globalData.ApiConstant.Address.list,{},{showLoad : false}).then((res) => {
				console.log(res)
				if (res.success) {
					this.addresses = res.data
				}
			}).catch((err) => {})
			.finally(() => {});
		},
		// --- 管理模式相关方法 ---
		startManage() {
			this.isManaging = true;
			// 确保所有地址都有 selected 属性并初始化为 false
			this.addresses.forEach(addr => {
				this.$set(addr, 'selected', false);
			});
		},
		cancelManage() {
			this.isManaging = false;
			// 取消所有选中状态
			this.addresses.forEach(addr => {
				this.$set(addr, 'selected', false);
			});
		},
		toggleSelect(address) {
			this.$set(address, 'selected', !address.selected);
		},
		deleteSelectedAddresses() {
			if (this.selectedAddresses.length === 0) {
				return;
			}

			const hasDefault = this.selectedAddresses.some(addr => addr.isDefault);
			if (hasDefault) {
				uni.showToast({
					title: '无法删除默认地址，请先设置其他地址为默认',
					icon: 'none'
				});
				return;
			}

			uni.showModal({
				title: '确认删除',
				content: `确定删除选中的 ${this.selectedAddresses.length} 个收货地址吗？`,
				confirmColor: '#f56c6c', // 确认按钮颜色变红
				success: (res) => {
					if (res.confirm) {
						// 过滤掉选中的地址
						this.addressesId = this.addresses.filter(addr => addr.selected).flatMap((item)=>{
							return item.id
						});
						app.globalData.Request.post(app.globalData.ApiConstant.Address.delete, {
							ids: this.addressesId.join(',')
						}).then((res) => {
							if(res.success){
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
								this.getAddressList();
							}
						}).finally(() => {
							this.cancelManage(); // 删除后退出管理模式
						});
					}
				}
			});
		},
		// --- 添加/编辑地址弹窗相关方法 ---
		addAddress() {
			this.isEditing = false;
			// 初始化一个空地址对象
			this.currentAddress = {
				name: '',
				phone: '',
				province: '',
				city: '',
				district: '',
				street: '',
				detailAddress: '',
				isDefault: false,
				region: '', // 用于 uni-data-picker
			};
			this.$refs.addressPopup.open('bottom');
			// 清除上次校验结果
			this.$nextTick(() => {
				this.$refs.form && this.$refs.form.clearValidate();
			});
		},
		editAddress(address) {
			this.isEditing = true;
			// 复制地址对象，避免直接修改原数组数据
			this.currentAddress = JSON.parse(JSON.stringify(address));
			this.$refs.addressPopup.open('bottom');
			// 清除上次校验结果
			this.$nextTick(() => {
				this.$refs.form && this.$refs.form.clearValidate();
			});
		},
		closeAddressForm() {
			this.$refs.addressPopup.close();
		},	
		onRegionChange(e) {
			const [province, city, district] = e.detail.value;
			this.currentAddress.province = province ? province.text : '';
			this.currentAddress.city = city ? city.text : '';
			this.currentAddress.district = district ? district.text : '';
			this.currentAddress.region = e.detail.value.map(item => item.value).join('-');
			// this.$refs.form.validateField("region"); // 手动触发校验
		},
		onDefaultChange(e) {
			this.currentAddress.isDefault = e.detail.value;
		},
		async saveAddress() {
			console.log(this.currentAddress)
			const formValid = await this.$refs.form.validate();
			if (!formValid) {
				return; // 校验失败
			}
			if(!this.currentAddress.region){
				uni.showToast({
					title: '请选择所在地区',
					icon: 'none'
				});
				return;
			}

			// 处理默认地址逻辑：如果当前地址被设为默认，则其他地址取消默认
			if (this.currentAddress.isDefault) {
				this.currentAddress.isDefault = 1
				this.addresses.forEach(addr => {
					if (addr.id !== this.currentAddress.id) { // 不修改当前地址自身
						addr.isDefault = 0
					}
				});
			}
			// 荡没有其他地址时，当前地址为默认地址
			if(this.addresses?.length == 0){
				this.currentAddress.isDefault = 1
			}

			this.currentAddress.isDefault = this.currentAddress.isDefault ? 1: 0;
			app.globalData.Request.post(app.globalData.ApiConstant.Address.save, this.currentAddress, 
			{showLoad : false}).then((res) => {
				if(res.success){
					uni.showToast({ title: '操作成功', icon: 'success' });
					this.getAddressList();
				}
			}).catch((err) => {})
			.finally(() => {});
			// if (this.isEditing) {
			// 	// 编辑模式：找到原地址并更新
			// 	const index = this.addresses.findIndex(addr => addr.id === this.currentAddress.id);
			// 	if (index !== -1) {
			// 		// 使用 $set 或直接赋值，确保响应式更新
			// 		this.$set(this.addresses, index, this.currentAddress);
			// 		// this.addresses[index] = this.currentAddress; // 或者直接这样，如果数据结构层级浅
			// 	}
				
			// } else {
			// 	// 添加模式：赋予新ID并加入列表
			// 	this.currentAddress.id = Date.now(); // 简单生成唯一ID，实际应用中应从后端获取
			// 	this.addresses.push(this.currentAddress);
			// 	uni.showToast({ title: '地址添加成功', icon: 'success' });
			// }
			this.closeAddressForm(); // 保存成功后关闭弹窗
			// 保存后列表会自动刷新，因为 addresses 数据被修改了
		},

		// --- 其他方法 ---
		selectAddress(address) {
			// 非管理模式下，点击地址项的处理逻辑，比如选中用于下单
			console.log('Selected address for use:', address);
			uni.showToast({
				title: `选中地址：${address.name}`,
				icon: 'none'
			});
			// 实际应用中，这里可能会 navigateBack 并带上地址信息
			// uni.navigateBack({ delta: 1, success: () => { /* 将地址信息传回 */ } });
		},

		// 辅助方法：根据省市区文本查找对应的 regionValue (简陋实现，实际应更完善)
		findRegionValue(provinceText, cityText, districtText) {
			if(!regionData) return '';
			let province = regionData.find(p => p.text === provinceText);
			if (!province) return '';
			let city = province.children.find(c => c.text === cityText);
			if (!city) return province.value; // 只匹配到省
			let district = city.children.find(d => d.text === districtText);
			if (!district) return `${province.value}-${city.value}`; // 只匹配到省市
			return `${province.value}-${city.value}-${district.value}`; // 匹配到省市区
		}
	}
};
</script>

<style lang="scss" scoped>
.address-list-page {
	background-color: #f7f8fa;
	min-height: 100vh;
	padding-bottom: calc(120rpx + constant(safe-area-inset-bottom)); /* 为底部按钮留出空间 */
	padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.address-list {
	padding: 24rpx;
	.address-item {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.03);

		.checkbox-wrapper {
			width: 60rpx; // 为选择框预留空间
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 20rpx; // 与地址信息留间距

			.checkbox {
				width: 40rpx;
				height: 40rpx;
				border: 1px solid #dcdfe6;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				box-sizing: border-box;
				&.checked {
					background-color: #ffc800; // 闲鱼黄
					border-color: #ffc800;
				}
			}
		}

		.address-info {
			flex-grow: 1;
			margin-right: 20rpx;
			.contact-line {
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;
				.name {
					font-size: 30rpx;
					font-weight: bold;
					color: #303133;
					margin-right: 20rpx;
				}
				.phone {
					font-size: 28rpx;
					color: #606266;
					margin-right: 15rpx;
				}
				.tag {
					font-size: 20rpx;
					padding: 2rpx 10rpx;
					border-radius: 4rpx;
					&.default-tag {
						background-color: #fef0f0; // 浅红色背景
						color: #f56c6c; // 红色文字
						border: 1px solid #fde2e2;
					}
				}
			}
			.address-detail {
				font-size: 26rpx;
				color: #606266;
				line-height: 1.5;
			}
		}
		.edit-action {
			padding: 10rpx; // 增大点击区域
			flex-shrink: 0; // 防止被压缩
		}
	}
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding-top: 200rpx;
	.empty-icon {
		width: 200rpx; // 根据实际图片调整
		margin-bottom: 30rpx;
	}
	.empty-text {
		font-size: 28rpx;
		color: #909399;
	}
}


.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	background-color: #fff;
	padding: 20rpx 24rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
	padding-bottom: calc(20rpx + constant(safe-area-inset-bottom)); /* 适配iPhone X等底部安全区域 */
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	z-index: 100;

	button {
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		&::after {
			border: none;
		}
	}
	.manage-btn {
		background-color: #f5f5f5;
		color: #303133;
		width: 30%;
		margin-right: 20rpx;
		&:disabled {
			background-color: #e0e0e0;
			color: #a0a0a0;
		}
	}
	.add-btn {
		background-color: #ffc800; // 闲鱼黄
		color: #303133; // 文字颜色深一点对比更清晰
		flex-grow: 1;
		font-weight: bold;
	}

	&.bottom-actions-manage {
		// 管理模式下的按钮样式
		.cancel-btn {
			background-color: #f5f5f5;
			color: #303133;
			width: 30%;
			margin-right: 20rpx;
		}
		.delete-btn {
			background-color: #f56c6c; // 红色
			color: #fff;
			flex-grow: 1;
			font-weight: bold;
			&:disabled {
				background-color: #fab6b6; // 变浅
				color: #fff;
			}
		}
	}
}


/* 添加/编辑地址弹窗样式 */
.address-form-popup {
	background-color: #fff;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
	padding: 30rpx 0 0; // 顶部有标题区域，底部有按钮区域

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx 20rpx;
		border-bottom: 1rpx solid #f5f5f5;
		.title {
			font-size: 34rpx;
			font-weight: bold;
			color: #303133;
		}
	}
	.popup-body {
		padding: 30rpx;
		max-height: 60vh; // 限制最大高度，防止表单过长溢出屏幕
		overflow-y: auto; // 内容超出时滚动

		// 调整表单项内边距和样式
		::v-deep .uni-forms-item {
			padding: 0; // 重置默认padding
			margin-bottom: 40rpx; // 调整表单项间距

			.uni-forms-item__label {
				width: 150rpx !important; // 固定label宽度
				font-size: 28rpx;
				color: #303133;
				padding-right: 20rpx;
				box-sizing: border-box;
			}
			.uni-forms-item__content {
				flex: 1; // 占据剩余空间
			}
			.uni-easyinput__content {
				border-color: #eee !important; // 调整输入框边框颜色
				background-color: #f9f9f9; // 调整输入框背景色
				border-radius: 8rpx;
				padding: 10rpx 15rpx;
				height: auto; // 高度自适应
				line-height: 1.5;
			}
			.uni-easyinput__placeholder {
				color: #c0c4cc;
			}
			.uni-easyinput__content[type=textarea] {
				min-height: 100rpx; // 文本域最小高度
				padding: 15rpx;
			}
			.uni-data-picker { // Province/City/District Picker
				.uni-stat__selector {
					padding: 10rpx 15rpx;
					border: 1px solid #eee;
					background-color: #f9f9f9;
					border-radius: 8rpx;
					color: #303133;
					min-height: unset;
				}
				.uni-stat__selector-placeholder {
					color: #c0c4cc;
				}
			}
			.uni-switch {
				transform: scale(0.8); // 缩小开关
				transform-origin: right center; // 从右边缩放
			}
		}
	}
	.popup-footer {
		padding: 20rpx 30rpx calc(20rpx + constant(safe-area-inset-bottom));
		padding: 20rpx 30rpx calc(20rpx + env(safe-area-inset-bottom));
		border-top: 1rpx solid #f5f5f5;

		.save-btn {
			background-color: #ffc800; // 闲鱼黄
			color: #303133;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			font-size: 32rpx;
			font-weight: bold;
		}
	}
}
</style>